<template>
  <div class="container">
    <van-nav-bar title="登录" />
    <van-form @submit="onSubmit">
      <van-cell-group inset>
        <van-field
          v-model="account"
          name="账号"
          placeholder="账号"
          left-icon="manager"
          :rules="userFormRules.account"
        />
        <van-field
          v-model="password"
          type="password"
          name="密码"
          placeholder="密码"
          left-icon="lock"
          :rules="userFormRules.password"
        />
      </van-cell-group>
      <div style="margin: 16px">
        <van-button round block type="primary" native-type="submit">
          登录
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { reactive, toRefs } from "vue";
import { login } from "../../api/user";
import { Toast } from "vant";
import { useStore } from "vuex";
import router from "../../router";

function userSubmit(user) {
  const store = useStore();
  const onSubmit = async () => {
    Toast.loading({
      message: "登录中...",
      forbidClick: true,
    });
    const loginParamString = JSON.stringify(user);
    const { data: res } = await login(loginParamString);
    if (res.code !== 200) return Toast.fail("用户名和密码错误");
    Toast.success("登录成功");
    store.commit("setUser", JSON.parse(res.data).token);
    window.sessionStorage.setItem("account", user.account);
    router.push("/study");
  };
  // 定义表单校验规则
  const userFormRules = {
    account: [{ required: true, message: "请输入账号" }],
    password: [
      { required: true, message: "请输入密码" },
      { pattern: /^\d{6}$/, message: "密码格式错误" },
    ],
  };
  return { onSubmit, userFormRules };
}
export default {
  setup() {
    const user = reactive({
      account: "",
      password: "",
    });
    return {
      ...toRefs(user),
      ...userSubmit(user),
    };
  },
};
</script>

<style scoped>
.container {
  height: 100vh;
  background: url(../../assets/image/登录图片.jpg) no-repeat;
  background-size: auto;
}
.van-form {
  margin-top: 330px;
}
.van-button {
  background-color: rgb(234, 215, 198);
  border: 0;
}
</style>